export default class AnimateFrameController {
  /**
   *
   * @param  {...Function} funs 需要执行的函数
   */
  constructor(...funs) {
    this.animationCallbacks = new Set(funs)
    this.startAnimate()
  }
  #requestId
  #isAnimate = false
  getRequsetId() {
    return this.#requestId
  }
  startAnimate() {
    if (this.animationCallbacks.size === 0) return
    if (this.#requestId) {
      this.stopAnimation()
      this.#requestId = null
    }
    const animate = () => {
      // this.animationCallbacks.forEach((f) => f())
      for (const f of this.animationCallbacks) {
        f()
      }
      this.#requestId = requestAnimationFrame(animate)
    }
    this.#requestId = requestAnimationFrame(animate)
    this.#isAnimate = true
  }
  addAnimationCallback(fn) {
    this.animationCallbacks.add(fn)
    if (this.animationCallbacks.size === 1) {
      this.startAnimate()
    } else if (this.animationCallbacks.size > 1 && !this.#isAnimate) {
      this.startAnimate()
    }
  }
  removeAnimationCallback(fnToRemove) {
    this.animationCallbacks.delete(fnToRemove)
    if (this.animationCallbacks.size === 0) {
      this.stopAnimation()
    }
  }
  stopAnimation() {
    cancelAnimationFrame(this.#requestId)
    this.#requestId = null
    this.#isAnimate = false
  }
}
